package com.xpgk.mvc.index;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.xpgk.mvc.base.BaseController;
import com.xpgk.mvc.bentryRegister.Customer;
import com.xpgk.mvc.codeSet.Code;
import com.xpgk.mvc.measurement.Temporary;
import com.xpgk.mvc.organization.Organization;
import com.xpgk.mvc.right.Right;
import com.xpgk.mvc.user.User;
import com.xpgk.mvc.warning.nonarrival.NonarrivalService;
import com.xpgk.tools.ToolDateTime;

public class IndexController extends BaseController {

	private static final Log log = Log.getLog(IndexController.class);

	private IndexService indexService;
	private NonarrivalService nonarrivalService;
	/**
	 * 首页
	 */
	public void index() {
		User user = getCUser(); // cookie认证自动登陆处理
		if (null != user) {// 后台
			List<Right> menuList = indexService.menu(user);
			setAttr("menuList", menuList);
			setAttr("user", user);
			render("/index/index.html");
		} else {
			render("/login/login.html");
		}
	}

	/**
	 * 管理中心
	 */
	public void center() {
		//Organization curOrgan = Organization.dao.findById(getCUserOrganIds());
		// String startTime = getPara("startTime",
		// ToolDateTime.getMonthOneDay(new Date()));
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		
		//String startTime = "2017-07-01";
		//String endTime = getPara("endTime", ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd));
		String orgid = getCUserOrganIds();
		Long cusNum = 0L;
		Long newCusNum = 0L;
		Double delWeightPrices = 0d;
		//indexService.getDelWeightSales(getCUserOrganIds(), sdf.format(new Date()));
		Double productPrices = 0d;
		//	indexService.getProductSales(getCUserOrganIds(), sdf.format(new Date()));
		Double delWeight =0d;
		String sql = "select * FROM sys_organization where parentIds = ?";
		if(getCUserOrganIds().equals("c9aebfe4912e4c07b4c7602b935154d6")||getCUserOrganIds().equals("ad6886c05b5c4117be0243d64974ac12")){
			orgid = null;
			 cusNum = indexService.getNewCustomerNum(orgid, null);
			 newCusNum = indexService.getNewCustomerNum(getCUserOrganIds(), sdf.format(new Date()));
			 delWeightPrices = 0d;
			//indexService.getDelWeightSales(getCUserOrganIds(), sdf.format(new Date()));
			 productPrices = 0d;
			//	indexService.getProductSales(getCUserOrganIds(), sdf.format(new Date()));
			delWeight = indexService.getDelWeight(getCUserOrganIds(), sdf.format(new Date()));
		}else{
			Organization organization = Organization.dao.findById(orgid);
			if(organization!=null){
				 int level = organization.getInt(Organization.column_level);
				 if(level==4){
						 cusNum = indexService.getNewCustomerNum(orgid, null);
						 newCusNum = indexService.getNewCustomerNum(getCUserOrganIds(), sdf.format(new Date()));
						 delWeightPrices = 0d;
						//indexService.getDelWeightSales(getCUserOrganIds(), sdf.format(new Date()));
						 productPrices = 0d;
						//	indexService.getProductSales(getCUserOrganIds(), sdf.format(new Date()));
						delWeight = indexService.getDelWeight(getCUserOrganIds(), sdf.format(new Date()));
				 }else if(level == 3){
					 List<Organization> orgList = Organization.dao.find(sql,orgid);
					 if(orgList!=null&&orgList.size()>0){
						 
						 for(int i = 0;i<orgList.size();i++){
							 Organization org = Organization.dao.findById(orgList.get(i).getStr(Organization.column_ids));
							 if(org!=null){
								 String orgIds = org.getStr(Organization.column_ids);
								 cusNum = cusNum+indexService.getNewCustomerNum(orgIds, null);
								 newCusNum = newCusNum+indexService.getNewCustomerNum(orgIds, sdf.format(new Date()));
								 delWeightPrices = 0d;
								//indexService.getDelWeightSales(getCUserOrganIds(), sdf.format(new Date()));
								 productPrices = 0d;
								//	indexService.getProductSales(getCUserOrganIds(), sdf.format(new Date()));
								delWeight = delWeight+indexService.getDelWeight(orgIds, sdf.format(new Date()));
								 
							 }
						 }
						
					 }
				 }
			}
		}
	
		
		int level = 0;
		Organization organization = Organization.dao.findById(getCUserOrganIds());
		if(organization!=null){
			level = organization.getInt(Organization.column_level);
		}
		setAttr("level", level);
		setAttr("cusNum", cusNum);
		setAttr("newCusNum", newCusNum);
		setAttr("delWeightPrices", delWeightPrices);
		setAttr("productPrices", productPrices); 
		setAttr("delWeight", delWeight); 
		//setAttr("startTime", startTime);
		//setAttr("endTime", endTime);
		setAttr("username", getCUser().getStr(User.column_username));
		render("/center/center.html");
	}

	/**
	 * 销售明细曲线图
	 * 
	 * @throws ParseException
	 */
	public void salesDetail() throws ParseException {
		Organization curOrgan = Organization.dao.findById(getCUserOrganIds());
		String startTime = ToolDateTime.getMonthOneDay(new Date());
		String endTime = getPara("endTime", ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd));
		List<String> days = ToolDateTime.getDaysByStartAndEnd(startTime, endTime);
		List<String> temp = new ArrayList<String>();
		List<String> list = new ArrayList<String>();
		List<String> dates = new ArrayList<String>();
		List<String> arr = new ArrayList<String>();
		int k = 0;
		for (int i = 0; i < days.size(); i++) {
			temp.add(days.get(i).substring(0, 5));
		}
		for (int i = 0; i < temp.size(); i++) {
			if (!list.contains(temp.get(i))) {
				list.add(temp.get(i));
			}
		}
		for (int j = 0; j < days.size(); j++) {
			if (days.get(j).substring(0, 5).equals(list.get(0))) {
				if (j == 0) {
					dates.add(days.get(j));
				} else {
					dates.add(days.get(j).substring(5, days.get(j).length()));
				}
				k = k + 1;
			}
		}
		for (int j = k; j < days.size(); j++) {
			if (days.get(j).substring(0, 5).equals(list.get(1))) {
				if (j == k) {
					arr.add(days.get(j));
				} else {
					arr.add(days.get(j).substring(5, days.get(j).length()));
				}
			}
		}
		dates.addAll(arr);
		if (null != curOrgan && days.size() > 0) {
			List<Double> weightSales = indexService.getDelWeightSalesDetail(curOrgan, days);
			List<Double> productSales = indexService.getProductSalesDetail(curOrgan, days);
			setAttr("weightSales", weightSales);
			setAttr("productSales", productSales);
		}
		setAttr("dates", dates);
		setAttr("startTime", startTime);
		setAttr("endTime", endTime);
		render("/center/saleTrend.html");
	}

	/**
	 * 公告
	 * 
	 */
	public void announce() {
		render("/center/announce.html");
	}

	/**
	 * 预警//当天
	 * 
	 * @throws ParseException
	 * 
	 */
	public void warninggk() throws ParseException {
		/*String startTime = "2017-07-01";// ToolDateTime.getMonthOneDay(new
										// Date()) 当月第一天
		String endTime = ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd);*/
		List<String> list = new ArrayList<String>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date = sdf.format(new Date());
		String orgid = getCUserOrganIds();
		//平称总数
		Long count1 = Db.findFirst(getSqlMy(IndexSQL.sqlId_weightNum),"0",orgid,date).getLong("count");
		list.add("当日平称顾客("+count1+")");
		//涨称
		Code parentCode = Code.cacheGet(Code.getCode("code_yjsz"));
		List<Code> codeList = Code.cacheGetChild(parentCode.getPKValue());
		float count = 3;
		for (Code code : codeList) {
			String id =code.get(Code.column_ids);
			if(id.equals("70a9d8f0f37943d2a2ba3ee05de22254")){
				count = Float.parseFloat((String) code.get(Code.column_code));
			}
		}
		count1 = Db.findFirst(getSqlMy(IndexSQL.sqlId_weightNum1),count+"",orgid,date).getLong("count");
		list.add("当日涨称"+count+"斤顾客("+count1+")");
		//掉秤
		 count = 3;
		for (Code code : codeList) {
			String id =code.get(Code.column_ids);
			if(id.equals("eb5b3258ce264e2f911b2d2aa2b90a23")){
				count = Float.parseFloat((String) code.get(Code.column_code));
			}
		}
		count1 = Db.findFirst(getSqlMy(IndexSQL.sqlId_weightNum2),-count+"",orgid,date).getLong("count");
		list.add("当日掉称"+count+"斤顾客("+count1+")");
			
		//<li>截止当日连续3天未到店顾客（1）</li>
		for (Code code : codeList) {
			String id =code.get(Code.column_ids);
			if(id.equals("adaa0f7e866b41ff9068a4a98f3366a9")){
				count = Float.parseFloat((String) code.get(Code.column_code));
			}
		}
		Map<String, Object> map =  splitPage.getQueryParam();
		map.put("organIds",orgid);
		map.put("date",date);
		map.put("wdts",count+"");
		List<String> users = nonarrivalService.findByDate(map);
		String cIds = "'cs'";
		if (users != null && users.size() > 0) {
			 cIds = nonarrivalService.sqlIn((String[]) users.toArray());
		}
		count1 = Db.findFirst(getSqlMy(IndexSQL.sqlId_nonarrival),orgid,cIds).getLong("count");
		list.add("截止当日连续"+count+"天未到店顾客("+count1+")");
		
		
		
		count = 3;
		for (Code code : codeList) {
			String id =code.get(Code.column_ids);
			if(id.equals("adaa0f7e866b41ff9068a4a98f3366a9")){
				count = Float.parseFloat((String) code.get(Code.column_code));
			}
		}	
		count1 = Db.findFirst(getSqlMy(IndexSQL.sqlId_courseDeficiencyNum),orgid,count+"",date).getLong("count");
		list.add("单疗程"+count+"次不足顾客("+count1+")");
		
		
		setAttr("list", list);

		render("/center/warninggk.html");
	}
	/**
	 * 预警//当月
	 * 
	 * @throws ParseException
	 * 
	 */
	public void warningmd() throws ParseException {
		String startTime = "2017-07-01";// ToolDateTime.getMonthOneDay(new
										// Date()) 当月第一天
		String endTime = ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd);
		Map<String, Integer> map = indexService.getWarning(getCUserOrganIds(), startTime, endTime);
		setAttr("map", map);

		render("/center/warningmd.html");
	}

	/**
	 * 疗程占比
	 * 
	 */
	public void treatmentRatio() {

		render("/center/coursePercent.html");
	}

	/**
	 * 门店使用情况
	 * 
	 */
	public void mdqk() {

		/*String sqlTem = "select * from sb_customer_temporary where  ISNULL(phone)";
		String sqlCus = "SELECT * from sb_customer where `name` = ? and dataStatus in ('1','2') and organIds = ?";
		List<Temporary> temporaries = Temporary.dao.find(sqlTem);
		for(int i = 0;i<temporaries.size();i++){
			String name = temporaries.get(i).getStr(Temporary.column_name);
			String organIds = temporaries.get(i).getStr(Temporary.column_organIds);
			Customer customer = Customer.dao.findFirst(sqlCus,name,organIds);
			
			temporaries.get(i).set(Temporary.column_phone, customer.getStr(Customer.column_phone));
			temporaries.get(i).update();
		}*/
		String sql = getSqlMy(IndexSQL.sqlId_mdqk);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal=Calendar.getInstance();
        cal.add(Calendar.DATE,-1);
        Date d=cal.getTime();
        String date = sdf.format(d);
        String result = "";
		List<Organization> organizations = Organization.dao.find(sql,date,getCUserOrganIds());
		for(int i = 0;i<organizations.size();i++){
			if(i!=(organizations.size()-1)){
				result = result+organizations.get(i).getStr("mdmc")+",";
			}else{
				result = result+organizations.get(i).getStr("mdmc");
			}
			
		}
		
		setAttr("result", result);
		
		setAttr("sizs", organizations.size());
		render("/center/mdqk.html");
	}

	/**
	 * 获取各疗程销售
	 * 
	 */
	public void getTreatmentRatio() {
		String startTime = "2017-07-01";// ToolDateTime.getMonthOneDay(new
										// Date()) 当月第一天
		String endTime = ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd);
		List<Record> result = indexService.getTreatmentRatio(getCUserOrganIds(), startTime, endTime);
		renderJson(result);
	}

	/**
	 * 产品占比
	 * 
	 */
	public void productRatio() {
		render("/center/productPercent.html");
	}

	/**
	 * 获取各产品销售
	 * 
	 */
	public void getProductRatio() {
		String startTime = "2017-07-01";// ToolDateTime.getMonthOneDay(new
										// Date()) 当月第一天
		String endTime = ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd);
		List<Record> result = indexService.getProductRatio(getCUserOrganIds(), startTime, endTime);
		renderJson(result);
	}
}
